import React, { useState, useEffect } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { Button } from "antd"; // 使用 Ant Design 的按钮组件

const Inform = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const { state } = location;
  const [animationStage, setAnimationStage] = useState(0);
  const [imageError, setImageError] = useState(false);

  useEffect(() => {
    const baguaTimer = setTimeout(() => setAnimationStage(1), 3000);
    const progressTimer = setTimeout(() => setAnimationStage(2), 5000);
    return () => {
      clearTimeout(baguaTimer);
      clearTimeout(progressTimer);
    };
  }, []);

  const handleImageError = () => setImageError(true);

  const handleViewResult = () => {
    navigate("/snakeFortune", { state });
  };

  const calculateWuXing = (birthYear) => {
    const heavenlyStems = ["甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"];
    const earthlyBranches = ["子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"];
    console.log(earthlyBranches);
    
    const wuXingMap = { 甲: "木", 乙: "木", 丙: "火", 丁: "火", 戊: "土", 己: "土", 庚: "金", 辛: "金", 壬: "水", 癸: "水" };
    const stemIndex = (birthYear - 4) % 10;
    const stem = heavenlyStems[stemIndex];
    const birthdayWuXing = wuXingMap[stem];
    const year2025WuXing = "木";
    console.log(year2025WuXing);
    
    let daXianWuXing = "", fortune = "", taboo = "";
    if (birthdayWuXing === "木") {
      daXianWuXing = "木强（木得生）";
      fortune = "2025年运势顺畅，适宜抓住机会，但需注意情绪管理。";
      taboo = "忌讳过于急躁，宜多与水、火属性的人合作。";
    } else if (birthdayWuXing === "火") {
      daXianWuXing = "火得生（木生火）";
      fortune = "2025年运势旺盛，但需注意过度消耗精力。";
      taboo = "忌讳过度劳累，宜多接触水属性事物。";
    } else if (birthdayWuXing === "土") {
      daXianWuXing = "土受克（木克土）";
      fortune = "2025年运势有阻力，宜低调行事。";
      taboo = "忌讳冒险，宜增强土气（如穿黄色）。";
    } else if (birthdayWuXing === "金") {
      daXianWuXing = "金受生（土生金）";
      fortune = "2025年运势平稳，有突破机会。";
      taboo = "忌讳锋芒毕露，宜接触土属性事物。";
    } else if (birthdayWuXing === "水") {
      daXianWuXing = "水得生（金生水）";
      fortune = "2025年运势平稳，适宜提升自己。";
      taboo = "忌讳保守，宜接触金属性事物。";
    }
    return { birthdayWuXing, daXianWuXing, fortune, taboo };
  };

  const wuXingInfo = state?.birthYear ? calculateWuXing(parseInt(state.birthYear)) : {
    birthdayWuXing: "未知",
    daXianWuXing: "未知",
    fortune: "请提供完整信息以获取运势。",
    taboo: "请提供完整信息以获取建议。",
  };

  return (
    <div
      style={{
        backgroundColor: "#252761",
        width: "600px",
        margin: "0 auto",
        paddingBottom: "60px",
        position: "relative",
        minHeight: "100vh",
        overflow: "auto",
      }}
    >
      {animationStage === 0 && (
        <div
          style={{
            position: "absolute",
            top: "50%",
            left: "50%",
            transform: "translate(-50%, -50%)",
            display: "flex",
            flexDirection: "column",
            alignItems: "center",
            zIndex: 10,
          }}
        >
          {imageError ? (
            <div style={{ width: "150px", height: "150px", backgroundColor: "#ccc", borderRadius: "50%", display: "flex", alignItems: "center", justifyContent: "center", color: "white", fontSize: "16px", textAlign: "center", animation: "spin 2s linear infinite" }}>
              八卦图片加载失败
            </div>
          ) : (
            <img
              src="https://th.bing.com/th/id/OIP.b2JVrY4fQI6Gjr8STL1ycgHaHa?rs=1&pid=ImgDetMain"
              alt="八卦转轮"
              style={{ width: "150px", height: "150px", animation: "spin 2s linear infinite", borderRadius: "50%", backgroundColor: "transparent" }}
              onError={handleImageError}
            />
          )}
          <p style={{ marginTop: "20px", fontSize: "18px", color: "#fff", textAlign: "center" }}>正在为您解析紫微运程...</p>
        </div>
      )}

      {animationStage === 1 && (
        <div
          style={{
            position: "absolute",
            top: "50%",
            left: "50%",
            transform: "translate(-50%, -50%)",
            width: "80%",
            textAlign: "center",
            zIndex: 10,
          }}
        >
          <p style={{ fontSize: "20px", color: "#ff4d4f", marginBottom: "10px" }}>正在生成你的2025年运程</p>
          <div style={{ width: "100%", height: "20px", backgroundColor: "#fff", border: "2px solid #ff4d4f", borderRadius: "10px", overflow: "hidden" }}>
            <div style={{ width: "0%", height: "100%", backgroundColor: "#ffa500", animation: "progress 2s ease-in-out forwards" }} />
          </div>
          <p style={{ marginTop: "10px", fontSize: "14px", color: "#fff" }}>正在生成你的2025年运程报告</p>
        </div>
      )}

      {animationStage === 2 && (
        <div>
          <img
            style={{ width: "100%", height: "auto", position: "absolute", top: 0, left: 0, zIndex: 1 }}
            src="https://zx.tengzhihh.com/ziweiliunianyunshi/static/bg.70eb6c9b.jpg"
            alt="背景图"
          />
          <div style={{ position: "relative", zIndex: 2, padding: "20px" }}>
            <div style={{ textAlign: "center", marginBottom: "20px", backgroundColor: "rgba(255, 255, 255, 0.9)", padding: "15px", border: "4px solid #ff4d4f", borderRadius: "10px" }}>
              <h2 style={{ color: "#ff4d4f", fontSize: "24px", marginBottom: "10px" }}>正在揭秘你的2025紫微运程</h2>
              <p style={{ color: "#333", fontSize: "18px" }}>你的生日五行为：{wuXingInfo.birthdayWuXing}</p>
              <p style={{ color: "#333", fontSize: "18px" }}>大限五行：{wuXingInfo.daXianWuXing}</p>
              <p style={{ color: "#333", fontSize: "16px", marginTop: "10px" }}>2025蛇年，{state?.name}，{wuXingInfo.fortune}</p>
            </div>
            <div style={{ display: "flex", flexDirection: "column", alignItems: "center", marginBottom: "20px" }}>
              <Button
                type="primary"
                onClick={handleViewResult}
                style={{
                  padding: "10px 30px",
                  backgroundColor: "#ff4d4f",
                  borderColor: "#ff4d4f",
                  borderRadius: "25px",
                  fontSize: "18px",
                  fontWeight: "bold",
                  height: "auto",
                  boxShadow: "0 4px 10px rgba(0, 0, 0, 0.2)",
                }}
              >
                查看详细运势
              </Button>
            </div>
            <div style={{ textAlign: "center", backgroundColor: "rgba(255, 255, 255, 0.9)", padding: "15px", border: "4px solid #ff4d4f", borderRadius: "10px" }}>
              <p style={{ color: "#333", fontSize: "16px" }}>命盘显示，2025年你的运势特点：{wuXingInfo.fortune}</p>
              <p style={{ color: "#ff4d4f", fontSize: "16px", fontWeight: "bold" }}>禁忌建议：{wuXingInfo.taboo}</p>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

const styles = `
  @keyframes spin {
    from { transform: rotate(0deg); }
    to { transform: rotate(360deg); }
  }
  @keyframes progress {
    from { width: 0%; }
    to { width: 100%; }
  }
`;

const styleSheet = document.createElement("style");
styleSheet.type = "text/css";
styleSheet.innerText = styles;
document.head.appendChild(styleSheet);

export default Inform;